<template>
  <div class="jiucha-table">
    <div class="content-wrapper">
      <div v-if="loading" class="loading-overlay">
        <i class="el-icon-loading"></i>
        <p>正在加载数据...</p>
      </div>

      <div class="records-container">
        <div class="records">
          <el-table
            :data="filteredRecords"
            style="width: 100%"
            :header-cell-style="{ fontSize: '16px' }"
            :row-class-name="tableRowClassName"
            :cell-style="{ borderColor: '#68d8fe' }"
            border
            class="custom-table"
          >
            <el-table-column prop="姓名" label="姓名" width="120" align="center"></el-table-column>
            <el-table-column prop="班级" label="班级" width="100" align="center"></el-table-column>
            <el-table-column prop="组别" label="组别" width="100" align="center"></el-table-column>
            <el-table-column prop="时间" label="时间" width="120" align="center">
              <template slot-scope="scope">
                {{ formatDate(scope.row.时间) }}
              </template>
            </el-table-column>
            <el-table-column prop="事项" label="事项" min-width="200" align="center"></el-table-column>
          </el-table>
          <div class="pagination">
            <button
              :disabled="currentPage === 1"
              @click="changePage(currentPage - 1)"
              class="page-btn"
            >
              <i class="el-icon-arrow-left"></i>
            </button>
            <span class="page-info">
              第 <b>{{ currentPage }}</b> / <b>{{ totalPages }}</b> 页
            </span>
            <button
              :disabled="currentPage === totalPages"
              @click="changePage(currentPage + 1)"
              class="page-btn"
            >
              <i class="el-icon-arrow-right"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'JiuchaTable',
  data() {
    return {
      loading: true,
      records: [],
      searchName: '',
      searchClass: '',
      searchGroup: '',
      searchReason: '',
      searchDate: '',
      searchTimeout: null,
      currentPage: 1,
      itemsPerPage: 15,
      total: 0
    }
  },
  computed: {
    filteredRecords() {
      if (!this.records.length) return [];

      let result = [...this.records];

      // 按姓名搜索
      if (this.searchName && this.searchName.trim()) {
        result = result.filter(record =>
          record.姓名 && record.姓名.includes(this.searchName.trim())
        );
      }

      // 按班级搜索
      if (this.searchClass && this.searchClass.trim()) {
        const searchClassTrimmed = this.searchClass.trim();
        result = result.filter(record => {
          if (!record.班级) return false;
          const classStr = String(record.班级 || '');
          return classStr.includes(searchClassTrimmed);
        });
      }

      // 按组别搜索
      if (this.searchGroup && this.searchGroup.trim()) {
        const searchGroupTrimmed = this.searchGroup.trim();
        result = result.filter(record => {
          if (!record.组别) return false;
          const groupStr = String(record.组别 || '');
          return groupStr.includes(searchGroupTrimmed);
        });
      }

      // 按事项搜索
      if (this.searchReason && this.searchReason.trim()) {
        result = result.filter(record =>
          record.事项 && record.事项.includes(this.searchReason.trim())
        );
      }

      // 按日期搜索
      if (this.searchDate) {
        result = result.filter(record => {
          if (!record.时间) return false;
          return record.时间 === this.searchDate;
        });
      }

      // 按日期降序排序（最新的在前面）
      result.sort((a, b) => {
        // 解析日期A
        let dateA;
        if (/^\d{8}$/.test(a.时间)) {
          const year = parseInt(a.时间.substring(0, 4));
          const month = parseInt(a.时间.substring(4, 6)) - 1;
          const day = parseInt(a.时间.substring(6, 8));
          dateA = new Date(year, month, day);
        } else {
          dateA = new Date(a.时间);
        }

        // 解析日期B
        let dateB;
        if (/^\d{8}$/.test(b.时间)) {
          const year = parseInt(b.时间.substring(0, 4));
          const month = parseInt(b.时间.substring(4, 6)) - 1;
          const day = parseInt(b.时间.substring(6, 8));
          dateB = new Date(year, month, day);
        } else {
          dateB = new Date(b.时间);
        }

        return dateB - dateA;
      });

      return result;
    },
    totalPages() {
      return Math.ceil(this.total / this.itemsPerPage);
    }
  },
  methods: {
    // 处理搜索
    handleSearch() {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
      }

      this.searchTimeout = setTimeout(() => {
        // 搜索逻辑已在计算属性中实现
      }, 300);
    },

    // 格式化日期显示
    formatDate(dateStr) {
      if (!dateStr) return '';

      // 处理数字格式的日期 (如 20250426)
      if (/^\d{8}$/.test(dateStr)) {
        const year = dateStr.substring(0, 4);
        const month = dateStr.substring(4, 6);
        const day = dateStr.substring(6, 8);
        return `${year}-${month}-${day}`;
      }

      // 尝试常规日期解析
      const date = new Date(dateStr);
      if (!isNaN(date.getTime())) {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      }

      // 如果无法解析，返回原始字符串
      return dateStr;
    },

    // 设置表格行样式
    tableRowClassName({ rowIndex }) {
      return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
    },

    // 获取纠察记录数据
    async loadData(page = 1) {
      this.loading = true;
      try {
        const response = await this.$overviewapi.getPicket({ pageNum: page, pageSize: this.itemsPerPage });
        if (response && response.code === '200' && Array.isArray(response.data)) {
          this.records = response.data.map(item => ({
            姓名: item.name || '',
            班级: item.classes || '',
            组别: item.groupName || '',
            时间: item.picketDate || item.createDate || '',
            事项: item.item || '',
            ...item
          }));
          this.total = response.total; // 从接口响应中获取total
          this.currentPage = page;
        } else {
          this.records = [];
        }
      } finally {
        this.loading = false;
      }
    },
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.loadData(page);
    }
  },
  created() {
    this.loadData(1);
  },
  mounted() {
    // 不再重复请求
  }
}
</script>

<style lang="scss" scoped>
.jiucha-table {
  color: #d3d6dd;
  width: 100%;
  height: 100%;
  position: relative;

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(29, 33, 39, 0.8);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 10;

    p {
      margin-top: 10px;
      color: #fff;
    }
  }

  .records-container {
    display: flex;
    justify-content: center;
    width: 100%;
    height: calc(100% - 80px);
  }

  .records {
    width: 100%;
    box-shadow: 0 0 25px rgba(0, 0, 0, 0.6), 0 0 5px rgba(104, 216, 254, 0.3);
    border-radius: 10px;
    overflow: hidden;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-table) {
    background-color: transparent;
    height: 100%;
    border: 2px solid #68d8fe;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(104, 216, 254, 0.3);

    th {
      background: linear-gradient(to bottom, #2c3e50, #1d2127) !important;
      border-bottom: 2px solid #68d8fe;
      border-right: 1px solid #68d8fe;
      font-weight: bold;
      padding: 15px 0;
      font-size: 16px !important;
      color: #68d8fe !important;
    }

    td {
      background-color: rgba(29, 33, 39, 0.8);
      border-bottom: 1px solid #68d8fe;
      border-right: 1px solid #68d8fe;
      color: #fff;
      padding: 12px 0;
      transition: background-color 0.2s ease;
    }

    .even-row td {
      background-color: rgba(29, 33, 39, 0.8);
    }

    .odd-row td {
      background-color: rgba(19, 25, 47, 0.8);
    }

    .el-table__row:hover > td {
      background-color: rgba(45, 50, 62, 0.9) !important;
    }

    .el-table__header-wrapper {
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
      overflow: hidden;
    }

    .el-table__body-wrapper {
      border-bottom-left-radius: 8px;
      border-bottom-right-radius: 8px;
      overflow-y: auto !important;
      overflow-x: hidden;
      max-height: 100%;
      scrollbar-width: thin;
      scrollbar-color: #68d8fe #1d2127;

      &::-webkit-scrollbar {
        width: 8px;
      }

      &::-webkit-scrollbar-track {
        background: #1d2127;
        border-radius: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #68d8fe;
        border-radius: 4px;
        border: 2px solid #1d2127;
      }
    }

    // Remove last column's right border
    th:last-child, td:last-child {
      border-right: none;
    }

    // Fix border issues
    &::before {
      display: none;
    }

    .el-table__fixed::before,
    .el-table__fixed-right::before {
      display: none;
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 4px;
    gap: 8px;
    background: transparent;
    border-radius: 6px;
    padding: 2px 8px;
    box-shadow: none;

    .page-btn {
      background: linear-gradient(90deg, #1e2746 0%, #223a5e 100%);
      border: none;
      color: #68d8fe;
      font-size: 14px;
      border-radius: 50%;
      width: 26px;
      height: 26px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background 0.2s, color 0.2s;
      cursor: pointer;
      box-shadow: none;

      &:hover:not(:disabled) {
        background: linear-gradient(90deg, #68d8fe 0%, #1e2746 100%);
        color: #fff;
      }
      &:disabled {
        color: #888;
        background: #222b44;
        cursor: not-allowed;
        opacity: 0.5;
      }
    }

    .page-info {
      color: #d3d6dd;
      font-size: 13px;
      font-weight: 500;
      letter-spacing: 1px;
      b {
        color: #68d8fe;
        font-size: 14px;
        font-weight: bold;
        margin: 0 2px;
      }
    }
  }
}
</style>
